//
//  DDAPPUpdateHelper.m
//  hnGovernment
//
//  Created by zhn on 2017/3/17.
//  Copyright © 2017年 安仔. All rights reserved.
//

#import "DDAPPUpdateHelper.h"
#import "DDbaseNetWork+Login.h"

@implementation DDAPPUpdateHelper
+ (instancetype)shareInstance {
    static DDAPPUpdateHelper *helper;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        helper = [[DDAPPUpdateHelper alloc]init];
    });
    return helper;
}

- (void)monitor {
    [DDNetWorkManager checkUpdateVersionSuccess:^(id result, DDcacheType cacheType, DDresultType resultType) {
        NSInteger updateCode = [result[@"data"][@"mustUpdate"]integerValue];
        NSString *updateURL = result[@"data"][@"downloadUrl"];
        if (updateCode == 0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showNormalAlertWithURL:updateURL];
            });
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showFourceUpdateAlertWithURL:updateURL];
            });
        }
    } failure:^(NSError *error) {
    }];
}

- (void)showNormalAlertWithURL:(NSString *)url {
    UIAlertController *updateAlert = [UIAlertController alertControllerWithTitle:@"有新版本发布" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *dismissAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    UIAlertAction *updateAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    }];
    [updateAlert addAction:dismissAction];
    [updateAlert addAction:updateAction];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:updateAlert animated:YES completion:nil];
}

- (void)showFourceUpdateAlertWithURL:(NSString *)url {
     UIAlertController *updateAlert = [UIAlertController alertControllerWithTitle:@"需要强制升级到新版本" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *updateAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    }];
    [updateAlert addAction:updateAction];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:updateAlert animated:YES completion:nil];
}
@end
